{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reversed Iteration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes we may want to iterate through an iterable but in **reverse** order.\n",
    "\n",
    "Of course, this means the collection being iterated must be finite."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python has a built-in function called `reversed()` to do this that will work with any type that implement the sequence protocol. But for iterables in general it's a little more complicated.\n",
    "\n",
    "Let's first build a custom iterable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this example we are going to build a custom iterable that returns cards from a 52-card deck.\n",
    "\n",
    "The deck will be in order of suits (Spades, Hearts, Diamonds and Clubs) and card values (from 2 (lowest) to Ace (highest)).\n",
    "\n",
    "We are going to use lazy loading - i.e. we are not going to pre-build our card deck."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We just need to recognize that each suit contains `13` cards, so an integer division of the index of the card in the deck will tell us which suit it is. But of course we start indexing at 0.\n",
    "\n",
    "**Example**\n",
    "\n",
    "If the requested card is the `6`th in the deck (i.e. index = `5`):\n",
    "\n",
    "`5 // 13 = 0` ==> first suit (Spades)\n",
    "\n",
    "If the requested card is the `13`th in the deck (i.e. index = `12`):\n",
    "\n",
    "`12 // 13 = 0` ==> first suit (Spades)\n",
    "\n",
    "If the requested card is the `14`th in the deck (i.e. index = `13`):\n",
    "\n",
    "`13 // 13 = 1` ==> second suit (Hearts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To determine which card in the suit we are interested in, we simply need to use the `%` operator, again recognizing that there are `13` cards in each suit:\n",
    "\n",
    "**Example**\n",
    "\n",
    "If the requested card is the `6`th in the deck (i.e. index = `5`):\n",
    "\n",
    "`5 % 13 = 5` ==> `5`th card in the suit\n",
    "\n",
    "If the requested card is the `13`th in the deck (i.e. index = `12`):\n",
    "\n",
    "`12 % 13 = 12` ==> `12`th card in the suit\n",
    "\n",
    "If the requested card is the `14`th in the deck (i.e. index = `13`):\n",
    "\n",
    "`13 % 13 = 0` ==> `1`st card in the suit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "_SUITS = ('Spades', 'Hearts', 'Diamonds', 'Clubs')\n",
    "_RANKS = tuple(range(2, 11) ) + tuple('JQKA')\n",
    "from collections import namedtuple\n",
    "\n",
    "Card = namedtuple('Card', 'rank suit')\n",
    "\n",
    "class CardDeck:\n",
    "    def __init__(self):\n",
    "        self.length = len(_SUITS) * len(_RANKS)\n",
    "\n",
    "    def __len__(self):\n",
    "        return self.length\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return self.CardDeckIterator(self.length)\n",
    "        \n",
    "    class CardDeckIterator:\n",
    "        def __init__(self, length):\n",
    "            self.length = length\n",
    "            self.i = 0\n",
    "            \n",
    "        def __iter__(self):\n",
    "            return self\n",
    "        \n",
    "        def __next__(self):\n",
    "            if self.i >= self.length:\n",
    "                raise StopIteration\n",
    "            else:\n",
    "                suit = _SUITS[self.i // len(_RANKS)]\n",
    "                rank = _RANKS[self.i % len(_RANKS)]\n",
    "                self.i += 1\n",
    "                return Card(rank, suit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now iterate over a deck of cards as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "deck = CardDeck()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Card(rank=2, suit='Spades')\n",
      "Card(rank=3, suit='Spades')\n",
      "Card(rank=4, suit='Spades')\n",
      "Card(rank=5, suit='Spades')\n",
      "Card(rank=6, suit='Spades')\n",
      "Card(rank=7, suit='Spades')\n",
      "Card(rank=8, suit='Spades')\n",
      "Card(rank=9, suit='Spades')\n",
      "Card(rank=10, suit='Spades')\n",
      "Card(rank='J', suit='Spades')\n",
      "Card(rank='Q', suit='Spades')\n",
      "Card(rank='K', suit='Spades')\n",
      "Card(rank='A', suit='Spades')\n",
      "Card(rank=2, suit='Hearts')\n",
      "Card(rank=3, suit='Hearts')\n",
      "Card(rank=4, suit='Hearts')\n",
      "Card(rank=5, suit='Hearts')\n",
      "Card(rank=6, suit='Hearts')\n",
      "Card(rank=7, suit='Hearts')\n",
      "Card(rank=8, suit='Hearts')\n",
      "Card(rank=9, suit='Hearts')\n",
      "Card(rank=10, suit='Hearts')\n",
      "Card(rank='J', suit='Hearts')\n",
      "Card(rank='Q', suit='Hearts')\n",
      "Card(rank='K', suit='Hearts')\n",
      "Card(rank='A', suit='Hearts')\n",
      "Card(rank=2, suit='Diamonds')\n",
      "Card(rank=3, suit='Diamonds')\n",
      "Card(rank=4, suit='Diamonds')\n",
      "Card(rank=5, suit='Diamonds')\n",
      "Card(rank=6, suit='Diamonds')\n",
      "Card(rank=7, suit='Diamonds')\n",
      "Card(rank=8, suit='Diamonds')\n",
      "Card(rank=9, suit='Diamonds')\n",
      "Card(rank=10, suit='Diamonds')\n",
      "Card(rank='J', suit='Diamonds')\n",
      "Card(rank='Q', suit='Diamonds')\n",
      "Card(rank='K', suit='Diamonds')\n",
      "Card(rank='A', suit='Diamonds')\n",
      "Card(rank=2, suit='Clubs')\n",
      "Card(rank=3, suit='Clubs')\n",
      "Card(rank=4, suit='Clubs')\n",
      "Card(rank=5, suit='Clubs')\n",
      "Card(rank=6, suit='Clubs')\n",
      "Card(rank=7, suit='Clubs')\n",
      "Card(rank=8, suit='Clubs')\n",
      "Card(rank=9, suit='Clubs')\n",
      "Card(rank=10, suit='Clubs')\n",
      "Card(rank='J', suit='Clubs')\n",
      "Card(rank='Q', suit='Clubs')\n",
      "Card(rank='K', suit='Clubs')\n",
      "Card(rank='A', suit='Clubs')\n"
     ]
    }
   ],
   "source": [
    "for card in deck:\n",
    "    print(card)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have our deck, how would we obtain the last `7` cards in reverse order from the deck?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One option is to generate a list of all the cards in the deck, then use a slice."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What about iterating in reverse? Using the same technique we generate a list that contains all the cards, reverse the list, and then iterate over the reversed list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "deck = list(CardDeck())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Card(rank='A', suit='Clubs'),\n",
       " Card(rank='K', suit='Clubs'),\n",
       " Card(rank='Q', suit='Clubs'),\n",
       " Card(rank='J', suit='Clubs'),\n",
       " Card(rank=10, suit='Clubs'),\n",
       " Card(rank=9, suit='Clubs'),\n",
       " Card(rank=8, suit='Clubs')]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deck[:-8:-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And to iterate backwards:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Card(rank='A', suit='Clubs')\n",
      "Card(rank='K', suit='Clubs')\n",
      "Card(rank='Q', suit='Clubs')\n",
      "Card(rank='J', suit='Clubs')\n",
      "Card(rank=10, suit='Clubs')\n",
      "Card(rank=9, suit='Clubs')\n",
      "Card(rank=8, suit='Clubs')\n",
      "Card(rank=7, suit='Clubs')\n",
      "Card(rank=6, suit='Clubs')\n",
      "Card(rank=5, suit='Clubs')\n",
      "Card(rank=4, suit='Clubs')\n",
      "Card(rank=3, suit='Clubs')\n",
      "Card(rank=2, suit='Clubs')\n",
      "Card(rank='A', suit='Diamonds')\n",
      "Card(rank='K', suit='Diamonds')\n",
      "Card(rank='Q', suit='Diamonds')\n",
      "Card(rank='J', suit='Diamonds')\n",
      "Card(rank=10, suit='Diamonds')\n",
      "Card(rank=9, suit='Diamonds')\n",
      "Card(rank=8, suit='Diamonds')\n",
      "Card(rank=7, suit='Diamonds')\n",
      "Card(rank=6, suit='Diamonds')\n",
      "Card(rank=5, suit='Diamonds')\n",
      "Card(rank=4, suit='Diamonds')\n",
      "Card(rank=3, suit='Diamonds')\n",
      "Card(rank=2, suit='Diamonds')\n",
      "Card(rank='A', suit='Hearts')\n",
      "Card(rank='K', suit='Hearts')\n",
      "Card(rank='Q', suit='Hearts')\n",
      "Card(rank='J', suit='Hearts')\n",
      "Card(rank=10, suit='Hearts')\n",
      "Card(rank=9, suit='Hearts')\n",
      "Card(rank=8, suit='Hearts')\n",
      "Card(rank=7, suit='Hearts')\n",
      "Card(rank=6, suit='Hearts')\n",
      "Card(rank=5, suit='Hearts')\n",
      "Card(rank=4, suit='Hearts')\n",
      "Card(rank=3, suit='Hearts')\n",
      "Card(rank=2, suit='Hearts')\n",
      "Card(rank='A', suit='Spades')\n",
      "Card(rank='K', suit='Spades')\n",
      "Card(rank='Q', suit='Spades')\n",
      "Card(rank='J', suit='Spades')\n",
      "Card(rank=10, suit='Spades')\n",
      "Card(rank=9, suit='Spades')\n",
      "Card(rank=8, suit='Spades')\n",
      "Card(rank=7, suit='Spades')\n",
      "Card(rank=6, suit='Spades')\n",
      "Card(rank=5, suit='Spades')\n",
      "Card(rank=4, suit='Spades')\n",
      "Card(rank=3, suit='Spades')\n",
      "Card(rank=2, suit='Spades')\n"
     ]
    }
   ],
   "source": [
    "deck = list(CardDeck())\n",
    "deck = deck[::-1]\n",
    "for card in deck:\n",
    "    print(card)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is kind of inefficient since we had to generate the entire list of cards, to then reverse it, and then only pick the first 7 cards from that reversed list."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Maybe we can try Python's built-in `reversed` function instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "deck = CardDeck()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'CardDeck' object is not reversible",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-9-486b5985b629>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mdeck\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mreversed\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdeck\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'CardDeck' object is not reversible"
     ]
    }
   ],
   "source": [
    "deck = reversed(deck)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, Python's `reversed` function will not work with out iterator. (It would work automatically with a sequence type, but in this case we don't have a sequence type)\n",
    "\n",
    "What to do?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need to somehow define a \"reverse\" iteration option for our iterator!\n",
    "\n",
    "We do so by defining the __reversed__ special method in our iterable and instructing out iterator to return elements in reverse order.\n",
    "\n",
    "If the `__reversed__` method is in our iterable, Python will use that to get the iterator when we call the `reverse()` function:\n",
    "\n",
    "Let's try that out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "_SUITS = ('Spades', 'Hearts', 'Diamonds', 'Clubs')\n",
    "_RANKS = tuple(range(2, 11) ) + ('J', 'Q', 'K', 'A')\n",
    "from collections import namedtuple\n",
    "\n",
    "Card = namedtuple('Card', 'rank suit')\n",
    "\n",
    "class CardDeck:\n",
    "    def __init__(self):\n",
    "        self.length = len(_SUITS) * len(_RANKS)\n",
    "\n",
    "    def __len__(self):\n",
    "        return self.length\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return self.CardDeckIterator(self.length)\n",
    "        \n",
    "    def __reversed__(self):\n",
    "        return self.CardDeckIterator(self.length, reverse=True)\n",
    "    \n",
    "    class CardDeckIterator:\n",
    "        def __init__(self, length, *, reverse=False):\n",
    "            self.length = length\n",
    "            self.reverse = reverse\n",
    "            self.i = 0\n",
    "            \n",
    "        def __iter__(self):\n",
    "            return self\n",
    "        \n",
    "        def __next__(self):\n",
    "            if self.i >= self.length:\n",
    "                raise StopIteration\n",
    "            else:\n",
    "                if self.reverse:\n",
    "                    index = self.length -1 - self.i\n",
    "                else:\n",
    "                    index = self.i\n",
    "                suit = _SUITS[index // len(_RANKS)]\n",
    "                rank = _RANKS[index % len(_RANKS)]\n",
    "                self.i += 1\n",
    "                return Card(rank, suit)\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "deck = CardDeck()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Card(rank=2, suit='Spades')\n",
      "Card(rank=3, suit='Spades')\n",
      "Card(rank=4, suit='Spades')\n",
      "Card(rank=5, suit='Spades')\n",
      "Card(rank=6, suit='Spades')\n",
      "Card(rank=7, suit='Spades')\n",
      "Card(rank=8, suit='Spades')\n",
      "Card(rank=9, suit='Spades')\n",
      "Card(rank=10, suit='Spades')\n",
      "Card(rank='J', suit='Spades')\n",
      "Card(rank='Q', suit='Spades')\n",
      "Card(rank='K', suit='Spades')\n",
      "Card(rank='A', suit='Spades')\n",
      "Card(rank=2, suit='Hearts')\n",
      "Card(rank=3, suit='Hearts')\n",
      "Card(rank=4, suit='Hearts')\n",
      "Card(rank=5, suit='Hearts')\n",
      "Card(rank=6, suit='Hearts')\n",
      "Card(rank=7, suit='Hearts')\n",
      "Card(rank=8, suit='Hearts')\n",
      "Card(rank=9, suit='Hearts')\n",
      "Card(rank=10, suit='Hearts')\n",
      "Card(rank='J', suit='Hearts')\n",
      "Card(rank='Q', suit='Hearts')\n",
      "Card(rank='K', suit='Hearts')\n",
      "Card(rank='A', suit='Hearts')\n",
      "Card(rank=2, suit='Diamonds')\n",
      "Card(rank=3, suit='Diamonds')\n",
      "Card(rank=4, suit='Diamonds')\n",
      "Card(rank=5, suit='Diamonds')\n",
      "Card(rank=6, suit='Diamonds')\n",
      "Card(rank=7, suit='Diamonds')\n",
      "Card(rank=8, suit='Diamonds')\n",
      "Card(rank=9, suit='Diamonds')\n",
      "Card(rank=10, suit='Diamonds')\n",
      "Card(rank='J', suit='Diamonds')\n",
      "Card(rank='Q', suit='Diamonds')\n",
      "Card(rank='K', suit='Diamonds')\n",
      "Card(rank='A', suit='Diamonds')\n",
      "Card(rank=2, suit='Clubs')\n",
      "Card(rank=3, suit='Clubs')\n",
      "Card(rank=4, suit='Clubs')\n",
      "Card(rank=5, suit='Clubs')\n",
      "Card(rank=6, suit='Clubs')\n",
      "Card(rank=7, suit='Clubs')\n",
      "Card(rank=8, suit='Clubs')\n",
      "Card(rank=9, suit='Clubs')\n",
      "Card(rank=10, suit='Clubs')\n",
      "Card(rank='J', suit='Clubs')\n",
      "Card(rank='Q', suit='Clubs')\n",
      "Card(rank='K', suit='Clubs')\n",
      "Card(rank='A', suit='Clubs')\n"
     ]
    }
   ],
   "source": [
    "for card in deck:\n",
    "    print(card)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Card(rank='A', suit='Clubs')\n",
      "Card(rank='K', suit='Clubs')\n",
      "Card(rank='Q', suit='Clubs')\n",
      "Card(rank='J', suit='Clubs')\n",
      "Card(rank=10, suit='Clubs')\n",
      "Card(rank=9, suit='Clubs')\n",
      "Card(rank=8, suit='Clubs')\n",
      "Card(rank=7, suit='Clubs')\n",
      "Card(rank=6, suit='Clubs')\n",
      "Card(rank=5, suit='Clubs')\n",
      "Card(rank=4, suit='Clubs')\n",
      "Card(rank=3, suit='Clubs')\n",
      "Card(rank=2, suit='Clubs')\n",
      "Card(rank='A', suit='Diamonds')\n",
      "Card(rank='K', suit='Diamonds')\n",
      "Card(rank='Q', suit='Diamonds')\n",
      "Card(rank='J', suit='Diamonds')\n",
      "Card(rank=10, suit='Diamonds')\n",
      "Card(rank=9, suit='Diamonds')\n",
      "Card(rank=8, suit='Diamonds')\n",
      "Card(rank=7, suit='Diamonds')\n",
      "Card(rank=6, suit='Diamonds')\n",
      "Card(rank=5, suit='Diamonds')\n",
      "Card(rank=4, suit='Diamonds')\n",
      "Card(rank=3, suit='Diamonds')\n",
      "Card(rank=2, suit='Diamonds')\n",
      "Card(rank='A', suit='Hearts')\n",
      "Card(rank='K', suit='Hearts')\n",
      "Card(rank='Q', suit='Hearts')\n",
      "Card(rank='J', suit='Hearts')\n",
      "Card(rank=10, suit='Hearts')\n",
      "Card(rank=9, suit='Hearts')\n",
      "Card(rank=8, suit='Hearts')\n",
      "Card(rank=7, suit='Hearts')\n",
      "Card(rank=6, suit='Hearts')\n",
      "Card(rank=5, suit='Hearts')\n",
      "Card(rank=4, suit='Hearts')\n",
      "Card(rank=3, suit='Hearts')\n",
      "Card(rank=2, suit='Hearts')\n",
      "Card(rank='A', suit='Spades')\n",
      "Card(rank='K', suit='Spades')\n",
      "Card(rank='Q', suit='Spades')\n",
      "Card(rank='J', suit='Spades')\n",
      "Card(rank=10, suit='Spades')\n",
      "Card(rank=9, suit='Spades')\n",
      "Card(rank=8, suit='Spades')\n",
      "Card(rank=7, suit='Spades')\n",
      "Card(rank=6, suit='Spades')\n",
      "Card(rank=5, suit='Spades')\n",
      "Card(rank=4, suit='Spades')\n",
      "Card(rank=3, suit='Spades')\n",
      "Card(rank=2, suit='Spades')\n"
     ]
    }
   ],
   "source": [
    "deck = reversed(CardDeck())\n",
    "for card in deck:\n",
    "    print(card)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Reversing Sequences"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I just want to point out that if we have a custom **sequence** type we don't need to worry about this.\n",
    "\n",
    "Let's see a quick example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Squares:\n",
    "    def __init__(self, length):\n",
    "        self.squares = [i **2 for i in range(length)]\n",
    "        \n",
    "    def __len__(self):\n",
    "        return len(self.squares)\n",
    "    \n",
    "    def __getitem__(self, s):\n",
    "        return self.squares[s]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sq = Squares(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "4\n",
      "9\n",
      "16\n"
     ]
    }
   ],
   "source": [
    "for num in Squares(5):\n",
    "    print(num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16\n",
      "9\n",
      "4\n",
      "1\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "for num in reversed(Squares(5)):\n",
    "    print(num)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see Python was able to automatically reverse the sequence for us."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also worth noting is that the `__len__` method **must** be implemented for `reversed()` to work:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Squares:\n",
    "    def __init__(self, length):\n",
    "        self.squares = [i **2 for i in range(length)]\n",
    "        \n",
    "#     def __len__(self):\n",
    "#         return len(self.squares)\n",
    "    \n",
    "    def __getitem__(self, s):\n",
    "        return self.squares[s]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "object of type 'Squares' has no len()",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-19-b22630289da4>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0mnum\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mreversed\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mSquares\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnum\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: object of type 'Squares' has no len()"
     ]
    }
   ],
   "source": [
    "for num in reversed(Squares(5)):\n",
    "    print(num)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition, we can override what is returned when the `reversed()` function is called on our custom sequence type. Here, I'll return the list of the integers themselves instead of squares just to make this really stand out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Squares:\n",
    "    def __init__(self, length):\n",
    "        self.length = length\n",
    "        self.squares = [i **2 for i in range(length)]\n",
    "        \n",
    "    def __len__(self):\n",
    "        return len(self.squares)\n",
    "    \n",
    "    def __getitem__(self, s):\n",
    "        return self.squares[s]\n",
    "    \n",
    "    def __reversed__(self):\n",
    "        print('__reversed__ called')\n",
    "        return [i for i in range(self.length-1, -1, -1)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "4\n",
      "9\n",
      "16\n"
     ]
    }
   ],
   "source": [
    "for num in Squares(5):\n",
    "    print(num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "__reversed__ called\n",
      "4\n",
      "3\n",
      "2\n",
      "1\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "for num in reversed(Squares(5)):\n",
    "    print(num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
